package com.ias.biz.test.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ias.common.constant.GlobalConstants;
import com.ias.common.security.util.SecurityUtils;
import com.ias.biz.test.mapper.AddressMapper;
import com.ias.biz.test.model.entity.Address;
import com.ias.biz.test.model.form.AddressForm;
import com.ias.biz.test.service.AddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 会员地址业务实现类
 *
 * @author magy
 * @since 2024/2/12
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    /**
     * 新增地址
     *
     * @param addressForm
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addAddress(AddressForm addressForm) {
        Long memberId = SecurityUtils.getMemberId();

        Address address = new Address();
        BeanUtil.copyProperties(addressForm, address);
        address.setMemberId(memberId);
        boolean result = this.save(address);
        if (result) {
            // 修改其他默认地址为非默认
            if (GlobalConstants.STATUS_YES.equals(addressForm.getDefaulted())) {
                this.update(new LambdaUpdateWrapper<Address>()
                        .eq(Address::getMemberId, memberId)
                        .eq(Address::getDefaulted, GlobalConstants.STATUS_YES)
                        .ne(Address::getId, address.getId())
                        .set(Address::getDefaulted, GlobalConstants.STATUS_YES)
                );
            }
        }
        return result;
    }


   
}
